/*
 * Based on TemperaturePacketReader
 */

import net.tinyos.packet.*;
import net.tinyos.util.*;
import net.tinyos.comm.*;

public class PacketListener extends Thread {
	
	protected PacketSource reader;
	protected HTTPRequest  request;
	
	public static final int    FUNCTION_TEMPERATURE_UPDATE = 1;
	
	public static final String REQUEST_URL_TEMPERATURE_UPDATE = "http://localhost/ac2/reading/add";


	final private double d1_fahrenheit = -39.3; // 3V VDD
	final private double d2_fahrenheit = 0.018; // 14 bit ADC
		
	public void run() {
        String source = null;
        PacketSource reader;
        
        if (source == null) {	
            reader = BuildSource.makePacketSource();
        } else {
            reader = BuildSource.makePacketSource(source);
        }
    	if (reader == null) {
    	    System.err.println("Invalid packet source (check your MOTECOM environment variable)");
    	    System.exit(2);
    	}
    	
    	request = new HTTPRequest();
    	
		try {
			reader.open(PrintStreamMessenger.err);
			for (;;) {
				byte[] packet = reader.readPacket();
				int f = (int) packet[10];
				if (f == FUNCTION_TEMPERATURE_UPDATE ) {
				    String requestUrl = REQUEST_URL_TEMPERATURE_UPDATE;
				    int    nodeId     = (int)packet[8];
				    double reading    = (256 * (packet[11] & 0xFF)) + (packet[12] & 0XFF);

				    reading     = d1_fahrenheit + (d2_fahrenheit * reading); // convert to F
				    requestUrl += "/zone/" +  nodeId + "/reading/" + reading;
				    request.send(requestUrl);
				    //System.out.println(requestUrl);
            	    //System.out.println();
				}
        	    //Dump.printPacket(System.out, packet);
        	    //System.out.println();
        	    System.out.flush();
			}
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
	}
}
